package com.dbq.fast.view;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.dbq.fast.R;
import com.dbq.fast.util.RudenessScreenHelper;


/**
 * Created by lxf on 2017/7/29.
 * arc
 */

public class CircleLoadingView extends View {

    private Paint mPaint;

    private float mWidth;
    private float mHeight;
    private float centerIconRadio;
    private Bitmap centerCompleteBitmap;
    private Bitmap centerNormalBitmap;
    private Bitmap centerPressedBitmap;
    private Bitmap encircleNormalIcon;
    private Bitmap encircleLoadingIcon;
    private Bitmap centerIcon;
    private Bitmap encircleIcon;
    private Bitmap encircleStatusIcon;
    private int startAngle;
    private ObjectAnimator mWaitAnimator;
    private boolean showEncircle;
    private int state = 0;// 0 待启动，1 正在启动，2 启动完成


    public CircleLoadingView(Context context) {
        this(context, null);
    }

    public CircleLoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleLoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleLoadingView);
        Drawable drawable = typedArray.getDrawable(R.styleable.CircleLoadingView_circleCenterNormalIcon);
        Drawable drawable1 = typedArray.getDrawable(R.styleable.CircleLoadingView_circleCenterCompletedIcon);
        Drawable drawable2 = typedArray.getDrawable(R.styleable.CircleLoadingView_circleEncircleLoadingIcon);
        Drawable drawable3 = typedArray.getDrawable(R.styleable.CircleLoadingView_circleEncircleNormalIcon);
        Drawable drawable4 = typedArray.getDrawable(R.styleable.CircleLoadingView_circleCenterPressedIcon);
        Drawable drawable5 = typedArray.getDrawable(R.styleable.CircleLoadingView_circleEncircleStatusIcon);
        centerIconRadio = typedArray.getFloat(R.styleable.CircleLoadingView_circleCenterIconRadio, 0);
        typedArray.recycle();
        centerIcon = centerNormalBitmap = ((BitmapDrawable) drawable).getBitmap();
        centerCompleteBitmap = ((BitmapDrawable) drawable1).getBitmap();
        encircleLoadingIcon = ((BitmapDrawable) drawable2).getBitmap();
        encircleIcon = encircleNormalIcon = ((BitmapDrawable) drawable3).getBitmap();
        centerPressedBitmap = ((BitmapDrawable) drawable4).getBitmap();
        encircleStatusIcon = ((BitmapDrawable) drawable5).getBitmap();
        if (centerIconRadio == 0) {
            centerIconRadio = centerIcon.getWidth();
        } else {
            centerIconRadio = RudenessScreenHelper.pt2px(getContext(), centerIconRadio);
        }

        initAttrs();

    }

    private void initAttrs() {
        mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setAntiAlias(true);
        mPaint.setFilterBitmap(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setColor(Color.BLACK);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (state == 0) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    centerIcon = centerPressedBitmap;
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    centerIcon = centerNormalBitmap;
                    invalidate();
                    break;
            }
        }

        return super.onTouchEvent(event);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
        mHeight = getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (showEncircle) {
            encircleIcon = encircleLoadingIcon;
//            encircleIcon = encircleStatusIcon;
        } else {
            encircleIcon = encircleNormalIcon;
        }
        drawCenterIcon(canvas);
        drawEncircle(canvas);
        //辅助线
//        canvas.drawLine(mWidth / 2, 0, mWidth / 2, mHeight, mPaint);
//        canvas.drawLine(0, mHeight / 2, mWidth, mWidth / 2, mPaint);
    }

    /**
     * 放缩 Bitmap
     *
     * @param bitmap
     * @param newWidth
     * @param newHeight
     * @return
     */
    private Bitmap changeBitmapSize(Bitmap bitmap, float newWidth, float newHeight) {
        if (newHeight == 0 || newWidth == 0) {
            return bitmap;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float scaleWidth = newWidth / width;
        float scaleHeight = newHeight / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.getWidth();
        bitmap.getHeight();

        return bitmap;
    }

    /**
     * 绘制环绕物品
     *
     * @param canvas
     */
    private void drawEncircle(Canvas canvas) {

        if(encircleIcon != encircleNormalIcon) {

            encircleLoadingIcon = changeBitmapSize(encircleLoadingIcon, mWidth, mHeight);
            float left = (mWidth - encircleLoadingIcon.getWidth()) / 2;
            float top = (mHeight - encircleLoadingIcon.getHeight()) / 2;

            canvas.save();

            //旋转内容
            Matrix matrix = new Matrix();
            float offsetX = encircleLoadingIcon.getWidth() / 2;
            float offsetY = encircleLoadingIcon.getHeight() / 2;
            matrix.postTranslate(-offsetX, -offsetY);
            matrix.postRotate(startAngle);
            matrix.postTranslate(left + offsetX, top + offsetY);
            canvas.drawBitmap(encircleLoadingIcon, matrix, mPaint);

            canvas.restore();

        }

//        encircleIcon = changeBitmapSize(encircleIcon, mWidth, mHeight);
//        float left1 = (mWidth - encircleIcon.getWidth()) / 2;
//        float top1 = (mHeight - encircleIcon.getHeight()) / 2;
//
//        canvas.drawBitmap(encircleIcon, left1, top1, null);
    }


    /**
     * 开启动画
     */
    public synchronized void startAnimation() {
        if (state != 0) {
            return;
        }
        state = 1;
        showEncircle = true;
        if (mWaitAnimator == null) {
            mWaitAnimator = ObjectAnimator.ofInt(this, "startAngle", 0, 360).setDuration(4000);
            mWaitAnimator.setRepeatMode(ObjectAnimator.RESTART);
            mWaitAnimator.setRepeatCount(ObjectAnimator.INFINITE);
            mWaitAnimator.setInterpolator(new LinearInterpolator());
        }
        centerIcon = centerNormalBitmap;
        if (!mWaitAnimator.isRunning()) {

            mWaitAnimator.start();
        }

    }

    /**
     * 暂停动画
     */
    private void stopAnimation() {
        if (mWaitAnimator != null) {
            if (mWaitAnimator.isRunning()) {
                mWaitAnimator.cancel();
            }
        }
        showEncircle = false;
        invalidate();

    }

    /**
     * 绘制中央的Icon
     *
     * @param canvas
     */
    private void drawCenterIcon(Canvas canvas) {
        centerIcon = changeBitmapSize(centerIcon, centerIconRadio, centerIconRadio);
        float left = (mWidth - centerIcon.getWidth()) / 2 /*- 3.5F*/;
        float top = (mHeight - centerIcon.getHeight()) / 2;
        canvas.drawBitmap(centerIcon, left, top, null);
    }

    public int getStartAngle() {
        return startAngle;
    }

    public void setStartAngle(int startAngle) {
        this.startAngle = startAngle;
        invalidate();
    }


    public void completed() {
        state = 2;
        centerIcon = centerCompleteBitmap;
        stopAnimation();
    }

    public void disconnect() {
        state = 0;
        centerIcon = centerNormalBitmap;
        encircleIcon = encircleNormalIcon;
        stopAnimation();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        releaseView();
    }

    /**
     * 释放 bitmap
     */
    private void releaseView() {
        centerCompleteBitmap = null;

        centerNormalBitmap = null;

        centerPressedBitmap = null;

        encircleNormalIcon = null;

        encircleLoadingIcon = null;
    }
}
